<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <div class="import-firefacstruct-wrap">
                <el-form label-width="100px" :model="baseInfoForm" ref="baseInfoForm" :rules="baseInfoFormRules" @submit.native.prevent>
                    <el-form-item label="所属单位：">
                        <el-input v-model="organizationName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="上级：" prop="relateFcfIds" id="relateFcfIds">
                        <el-select v-model="baseInfoForm.relateFcfIds" 
                            placeholder="请选择父节点消防设施，没有则留空"
                            filterable
                            :filter-method="getFcfOptions"
                            :loading="relateFcIdsSelectloading"
                            :disabled="showProgress">
                            <el-option
                                v-for="item in relateFcOptions"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            </el-option>
                            <el-pagination
                                @current-change="handleCurrentChange"
                                :current-page.sync="relateFcPageIndex"
                                small
                                layout="total, prev, pager, next"
                                :total="relateFcTotal">
                            </el-pagination>
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-upload
                    v-show="!showProgress"
                    class="upload-asset"
                    ref="upload"
                    drag
                    name="excelfile"
                    accept=".xls,.xlsx"
                    :data="parames"
                    :action="actionUrl"
                    :before-upload="beforeUpload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :file-list="fileList"
                    :auto-upload="false"
                    multiple>
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">*只能上传xls/xlsx文件</div>
                </el-upload>
                <el-row v-if="showProgress" type="flex" justify="center">
                    <el-progress type="circle" :percentage="importProgressNum" :status="importStatus"></el-progress>
                </el-row>
                <p v-if="showProgress" class="text-center" :class="{'color-4': importProgressNum!=100, 'color-3': importProgressNum==100}">{{importProgressNum != 100 ? '正在导入中，请稍等...' : '导入成功'}}</p>
                <el-row class="verifyidentity-button">
                    <el-button @click.stop="closeFun" round>取消</el-button>
                    <el-button type="primary" @click="submitUpload" round :disabled="showProgress">开始导入</el-button>
                </el-row>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import { setTimeout } from 'timers';
import { getFcfSelectList, getImportFNum } from '@/api/fcf'

var loadingObj = null
var t
export default {
  name:'ImportTemp',
  props: {
    organizationId: {
      required: true
    },
    organizationName: {
      required: true
    },
    closeFun: {
      type: Function,
      required: true,
    }
  },
  data() {
    return {
        baseInfoForm: {
            relateFcfIds: ''
        },
        baseInfoFormRules: {
            // relateFcfIds: [
            //     { required: true, message: '消防设施', trigger: 'change' }
            // ]
        },
        // 关联消防设施
        relateFcIdsSelectloading: false,
        relateFcOptions: [],
        relateFcPageIndex: 1,
        relateFcTotal: 0,
        // 上传文件
        // showUpload: true,
        fileList: [],
        actionUrl: this.GLOBAL.baseURL + 'fcf/importFTemplate',
        parames: {
            organizationId: this.organizationId,
            parentId: 0
        },
        // 导入过程数据
        showProgress: false, // 是否显示进度条
        importProgressNum: 0, // 导入进度
        importStatus: null, // 导入状态
        importKey: null // 导入标识
    }
  },
  created() {
    let that = this
    that.getFcfOptions()
  },
  methods: {
    // 获取消防设施
    getFcfOptions(name, pageChange) {
        let that = this
        // 重新搜索时页码复原   
        if(!pageChange) {
            this.relateFcPageIndex = 1
        }
        let parames = {
            fbsId: 0,
            organizationId: that.organizationId,
            parentId: 0,
            pageIndex: that.relateFcPageIndex - 1,
            pageSize: 10,
            name: name || ''
        } 
        that.relateFcIdsSelectloading = true
        getFcfSelectList(parames).then(res => {
            if(res.status === 200) {
                that.relateFcOptions = res.data
                that.relateFcTotal = res.total
            }
            that.relateFcIdsSelectloading = false
        })
    },
    handleCurrentChange(currentpage) {
        this.relateFcPageIndex = currentpage
        this.getFcfOptions($('#relateFcfIds .el-select__input').val(), true)
    },
    submitUpload() {
        let that = this
        // 校验表单
        that.$refs['baseInfoForm'].validate((valid) => {
            if (valid) {
                // 开始后台校验
                loadingObj = that.$loading({
                    lock: true,
                    text: "校验数据中，请稍等...",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)"
                })
                that.$refs.upload.submit()
            }
        })
    },
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.')+1)				
      const isXSL = testmsg === 'xls'
      const isXLSX = testmsg === 'xlsx'
      if (!isXSL && !isXLSX) {
        this.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning'
        });
        return false;
      }
    },
    handleRemove(file, fileList) {
    //   console.log(file, fileList)
    },
    handlePreview(file) {
    //   console.log(file)
    },
    handleSuccess(res) {
        // 关闭数据监测loading
        loadingObj.close()
        if(res.status === 200) {
            if(res.data.status === 1) {
                this.$message.warning(res.data.errInfo)
            } else {
                // 显示导入进度
                this.showImportProcess(res.data.redisKey)
            }
            // this.$message.success("文件上传成功！")
        } else {
            this.$message.warning(res.info)
        }
    },
    handleError(err, file, fileList) {
        this.$message.error("文件上传失败！");
    },
    // 导入进度
    showImportProcess(id) {
        if(id) {
            this.importKey = id
            this.showProgress = true
            this.getImportResult()
        } else {
            this.$message.error("文件导入错误！");
        }
    },
    // 获取导入结果
    getImportResult() {
        let that = this
        if( that.importStatus != 'warning' ) {
            getImportFNum({
                key: that.importKey
            }).then(res => {
                if(res.status === 200 && res.data) {
                    let data = JSON.parse(res.data) 
                    if(data.importNum) {
                        that.importProgressNum = Math.round((data.importNum / data.total) * 100)
                    }
                    if(that.importProgressNum == 100) {
                        // 导入完成
                        that.importStatus = 'success'
                        // 关闭弹框
                        // that.$message.success("数据导入成功！")
                        // that.closeFun(true)
                    } else if( that.importStatus != 'warning' ) {
                        // 导入未完成，每隔1S获取下导入情况
                        t = setTimeout(() => {
                            that.getImportResult()
                        }, 1000)
                    }
                } else {
                    that.importStatus = 'exception'
                }
            })
        }
    },
    // 获取是否需要回滚结果
    getNeedBackFlag() {
        if(this.showProgress && this.importProgressNum < 100) {
            // 更改导入状态
            this.importStatus = 'warning'
            // 清除定时器
            if(t) {
                clearTimeout(t)
            }
            return this.importKey
        } else {
            return false
        }
    },
    // 继续导入
    goOnImport() {
        this.importStatus = null
        this.getImportResult()
    }
  },
  watch: {
    relateFcfIdsSelect(val, oldVal) {
        if(val && val !== oldVal) {
            // this.showUpload = false
            this.parames.parentId = val
            // this.showUpload = true
        }
    }
  },
  computed: {
    relateFcfIdsSelect() {
        return this.baseInfoForm.relateFcfIds
    }
  }
}
</script>
<style lang="scss">
.import-firefacstruct-wrap {
    .upload-asset {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .verifyidentity-button {
        margin-top: 20px;
    }
}
</style>
